﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace UDPServer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int nRecvByte;
            byte[] data = new byte[1024];
            // 定义一个网络端点
            IPEndPoint IPAdress = new IPEndPoint(IPAddress.Any,9050);
            // 定义一个数据报类型的Socket
            // SocketType.Dgram:使用数据报协议
            // ProtocolType:UDP协议
            Socket ClientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            // Socket与本地的终端结点绑定
            ClientSocket.Bind(IPAdress);
            Console.WriteLine("Wait For a Client!");
            // 定义一个要发送的IP地址
            IPEndPoint Sender = new IPEndPoint(IPAddress.Any,0);
            EndPoint IPRemote = (IPEndPoint)Sender;
            // 接受数据报并存储源终结点
            nRecvByte = ClientSocket.ReceiveFrom(data,SocketFlags.None,ref IPRemote);
            Console.WriteLine("Message Receive From:{0}:", IPRemote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data,0,nRecvByte));
            string strWelcome = "Welcome to My Test Server!";
            data = Encoding.ASCII.GetBytes(strWelcome);
            ClientSocket.SendTo(data,SocketFlags.None,IPRemote);
            while (true)
            {
                //接收客户端的数据并且发回 
                data = new byte[1024];
                nRecvByte = ClientSocket.ReceiveFrom(data,ref IPRemote);
                Console.WriteLine(Encoding.ASCII.GetString(data,0, nRecvByte));
                ClientSocket.SendTo(data,IPRemote);
            }
        }
    }
}
